package com.zcmob.web.admanagement.parser;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import com.zcmob.web.admanagement.db.AppDao;
import com.zcmob.web.admanagement.exception.AppExsitException;
import com.zcmob.web.admanagement.util.PropsUtils;
import com.zcmob.web.admanagement.util.StringUtils;
import com.zcmob.web.admanagement.vo.AppInfo;

public class GetInfo {

    public GetInfo() {

    }

    private static ZipEntry getIconzipEntry(ZipFile zFile, String iconpath){
        ZipEntry iconEntry = zFile.getEntry(iconpath);
        
        if (iconEntry == null) {
            iconEntry = zFile.getEntry(iconpath.replace("drawable", "drawable-hdpi"));
        }
        if (iconEntry == null) {
            iconEntry = zFile.getEntry(iconpath.replace("drawable", "drawable-ldpi"));
        }
        if (iconEntry == null) {
            iconEntry = zFile.getEntry(iconpath.replace("drawable", "drawable-mdpi"));
        }
        if (iconEntry == null) {
            iconEntry = zFile.getEntry(iconpath.replace("drawable", "drawable-xdpi"));
        }
        
        return iconEntry;
    }

    public static AppInfo getApkInfo(String apkpath) throws AppExsitException {
        AppInfo appinfo = new AppInfo();
        InputStream stream = null;
        InputStream iconStram = null;
        FileOutputStream iconOut = null;
        try {
            ZipFile zFile = new ZipFile(apkpath);
            ZipEntry entry = zFile.getEntry("AndroidManifest.xml");
            stream = zFile.getInputStream(entry);
            appinfo = resolve(stream);
            
            if (AppDao.getInstance().isAppExit(appinfo.getPackagename())) {
                throw new AppExsitException();
            }
            
            String iconName = Unzip.getIcons(apkpath);
            appinfo.setIconNameInAPK(iconName);
            ZipEntry iconEntry = getIconzipEntry(zFile, iconName);
            iconStram = zFile.getInputStream(iconEntry);
            String iconFilePath = PropsUtils.getProperty("icontmpserverpath") + appinfo.getPackagename() + ".png";
           
            iconOut = new FileOutputStream(new File(iconFilePath));
            int c;
            byte b[] = new byte[4 * 1024];
            while ((c = iconStram.read(b)) != -1) {
                iconOut.write(b, 0, c);
            }            
            appinfo.setApk_size(new File(apkpath).length());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (iconStram != null) {
                    iconStram.close();
                }
                if (iconOut != null) {
                    iconOut.close();
                }
                if (stream != null) {
                    stream.close();
                }
               
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return appinfo;
    }

    private static AppInfo resolve(InputStream stream) {
        AppInfo appinfo = new AppInfo();
        try {

            SAXParserFactory parserFactory = SAXParserFactory.newInstance();
            parserFactory.setValidating(false);
            parserFactory.setNamespaceAware(false);
            MyXmlResolve saxParserInstance = new MyXmlResolve();

            String strContent = AXMLPrinter2.parse(stream);
            byte[] by = strContent.getBytes("utf-8");
            ByteArrayInputStream bais = new ByteArrayInputStream(by);
            SAXParser parser = parserFactory.newSAXParser();
            parser.parse(bais, saxParserInstance);
            bais.close();
            parser = null;
            String iconName = "res/drawable/ic_launcher.png";
            if (!StringUtils.isNullOrEmpty(saxParserInstance.getIconName())) {
                iconName = saxParserInstance.getIconName().replace("@", "res/");
            }
            appinfo.setIconNameInAPK(iconName);
            appinfo.setPackagename(saxParserInstance.getStrpackage());
            appinfo.setVersion(saxParserInstance.getStrversion());

        } catch (UnsupportedEncodingException e) {
            System.out.println("UnsupportedEncodingException");

        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException");

        } catch (ParserConfigurationException e) {
            System.out.println("ParserConfigurationException");

        } catch (SAXException e) {
            System.out.println("SAXException");

        } catch (IOException e) {
            System.out.println("IOEXCEPTION");

        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return appinfo;
    }

    /**
     * ��ȡ�ļ����µ��ļ���
     */
    private static ArrayList<String> getFiles(String path) {
        ArrayList<String> listAPKFiles = null;
        File files = null;
        try {
            files = new File(path);
            String[] strFiles = files.list(new FilterAPKGetWithCMD());
            if (strFiles.length > 0) {
                listAPKFiles = new ArrayList<String>();
                for (int i = 0; i < strFiles.length; i++) {
                    String strFile = strFiles[i];
                    if (strFile.length() > 0) {
                        listAPKFiles.add(path + strFile);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        files = null;
        return listAPKFiles;
    }

    public static void main(String[] args) {
        try {
            PropsUtils.load2SystemProperties(new File("E:\\tools\\work_space\\zcmob\\src\\env.properties"));
        } catch (IOException e) {

        }
//        System.out.println(getApkInfo("E:\\otherandroid\\com.gker.five.apk"));
    }
}

/**
 * �����ļ���׺
 * 
 * @author Administrator
 * 
 */
class FilterAPKGetWithCMD implements FilenameFilter {

    @Override
    public boolean accept(File dir, String name) {
        boolean isapk = false;
        if (name.indexOf(".apk") != -1) {
            isapk = true;
        }
        return isapk;
    }
}
